package com.body.park.user.config;

import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author chaoxian.wu
 * @DATE 2022/3/27 11:13
 */
@RefreshScope
@Configuration
public class RedisSonConfiguration {

    @Value("${spring.redis.host}")
    private String address;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private String database;

    @Value("${spring.redis.timeout}")
    private String timeout;
    //预估需要插入的值
    @Value("${bloomfilter.expected-insertions}")
    private Long expectedInsertions;
    //容错率
    @Value("${bloomfilter.false-probability}")
    private double falseProbability;

    @Bean
    public RedissonClient redisson() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress(address())
                .setPassword(password)
                .setDatabase(Integer.parseInt(database))
                .setConnectTimeout(Integer.parseInt(timeout));
        return Redisson.create(config);
    }

    /**
     * 注入布隆过滤器
     * @return
     */
    @Bean
    public RBloomFilter bloomFilter() {
        RBloomFilter<Object> bloomFilter = redisson().getBloomFilter("bloom-filter");
        bloomFilter.tryInit(expectedInsertions, falseProbability);
        return bloomFilter;
    }

    /**
     * 生成address
     * @return
     */
    private String address() {
        return "redis://" + address + ":" + port;
    }
}
